<script setup lang="ts">
import { ref, watchEffect } from 'vue';
import myAxios from "../plugins/myAxios.ts";
import {Toast} from "vant";
import UserCardList from "../components/UserCardList.vue";
import {UserType} from "../models/user";
const isMatchMode = ref<boolean>(false);
const userList = ref([]);
const loading = ref(true);
// const route = useRoute()
const searchText = ref('');
// const {tags} = route.query
const images = [
    "https://img2.baidu.com/it/u=556745099,1950842476&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=281",
    "https://img1.baidu.com/it/u=853203586,2979748383&fm=253&fmt=auto&app=138&f=PNG?w=605&h=371",
    "https://img0.baidu.com/it/u=802106576,2959941761&fm=253&fmt=auto&app=138&f=PNG?w=622&h=415",
    "https://img1.baidu.com/it/u=4267177488,2608174372&fm=253&fmt=auto&app=138&f=JPEG?w=892&h=500",
    "https://img2.baidu.com/it/u=1408899786,3098693376&fm=253&fmt=auto&app=138&f=JPEG?w=440&h=319",
    "https://img1.mydrivers.com/img/20220421/S1e92d1a6-7cd6-41f7-a460-6e47d4d27ccf.png"
]

/**
 * 加载数据
 */
const loadData = async () => {
  loading.value = true;
  let userListData;

  if (isMatchMode.value) {
    // 心动模式
    try {
      const response = await myAxios.get('/user/match', { params: { num: 10 } });
      userListData = response.data;
    } catch (error) {
      Toast.fail('请求失败');
    }
  } else {
    // 普通模式
    if (searchText.value.trim() !== '') {
      // 搜索模式
      try {
        const response = await myAxios.post('/user/search', { searchText: searchText.value.trim() });
        userListData = response.data;
        if (userListData.length <= 0) {
          Toast.fail('无搜索用户');
        }
      } catch (error) {
        Toast.fail('请求失败');
      }
    } else {
      // 推荐模式
      try {
        const response = await myAxios.get('/user/recommend', {
          params: { pageSize: 10, pageNum: 1 },
        });
        if (response.code === 40101) {
          Toast.fail(response.message + '，请登录');
        } else {
          userListData = response.data.records; // 根据您的后端响应结构进行调整
        }
      } catch (error) {
        Toast.fail('请求失败');
      }
    }
  }

  if (userListData) {
    userListData = userListData.map((user: UserType) => ({
      ...user,
      tags: user.tags ? JSON.parse(user.tags) : [],
    }));
    userList.value = userListData;
  }

  loading.value = false;
};

watchEffect(() => {
  // 这里可以添加一些条件来决定是否重新加载数据
  // 例如：watchEffect(() => { if (someCondition) loadData(); })
  // 但由于您想要在页面加载时立即加载数据，所以直接调用 loadData() 是可以的
  loadData();
});

const onRefresh = () => {
  setTimeout(async () => {
    loading.value = true; // 开始加载数据前设置加载状态
    let userListData;

    try {
      const response = await myAxios.get('/user/random', {
        params: {pageSize: 10}, // 根据需要调整参数
      });
      // 注意：这里应该根据实际的响应结构来处理数据
      // 假设后端返回的数据结构中没有 code 字段，或者 code 字段不是用于错误处理的
      // 如果需要处理错误，请根据您的后端响应结构进行调整
      userListData = response.data;
    } catch (error) {
      Toast.fail('请求失败');
    } finally {
      if (userListData) {
        userListData = userListData.map((user: UserType) => ({
          ...user,
          tags: user.tags ? JSON.parse(user.tags) : [],
        }));
        userList.value = userListData;
      }
      loading.value = false; // 请求完成后更新加载状态
      // Toast('刷新成功');
      Toast('发现新伙伴~');
    }

    // 注意：这里不需要再次调用 loadData()，因为您已经在 setTimeout 内部处理了随机推荐逻辑
  }, 1000); // 延迟 1 秒后执行，这通常是为了模拟下拉刷新的动画效果
};

</script>

<template>

  <van-pull-refresh v-model="loading" @refresh="onRefresh">

  <van-notice-bar
      color="#1989fa"
      background="#ecf9ff"
      left-icon="volume-o"
      style="margin-bottom: 10px"
      text="欢迎使用Code Partner，在这里寻找和自己方向相同或者需要合作的伙伴一起愉快的合作交流吧！"
  />
  <div style="position: relative;height: 100%;width: 100%">
    <van-swipe class="my-swipe" :autoplay="4000" indicator-color="white" lazy-render
               style="width: 90%;height: 150px;margin: 0 auto">
      <van-swipe-item v-for="image in images" :key="image">
        <img :src="image" style="width: 100%;height: 150px"/>
      </van-swipe-item>
    </van-swipe>
    <van-cell center title="心动模式" style="font-weight: bold">
      <template #right-icon>
        <van-switch v-model="isMatchMode" size="26" background="#39a9ed" active-color="#39a9ed"/>
      </template>
    </van-cell>
    <van-search
        v-if="!isMatchMode"
        v-model="searchText"
        placeholder="请输入搜索关键词"
        show-action
        @search="loadData"
    >
      <!--    <template #action>-->
      <!--      <div style="color: #1989fa" @click="loadData">搜索</div>-->
      <!--    </template>-->
    </van-search>
    <div>
      <user-card-list :user-list="userList" :loading="loading"/>
    </div>
    <van-empty v-if="!userList || userList.length < 1" description="数据为空"/>
  </div>

  </van-pull-refresh>

</template>

<style scoped>
.my-swipe .van-swipe-item {
  color: #fff;
  font-size: 20px;
  line-height: 150px;
  text-align: center;
  background-color: #39a9ed;
}

.my-swipe {
  margin: 15px;
  border-radius: 3%;
}
</style>
